<template>
    <div class="change-password-container">
        <div class="change-password" v-loading="loading">
            <h2 style="margin-bottom: 30px;">{{ title }}</h2>
            <a-steps :current="step" size="small" class="steps">
                <a-step title="输入手机号" :status="step > 0 ? 'finish' : 'process'" />
                <a-step title="验证验证码" :status="step > 1 ? 'finish' : step === 1 ? 'process' : 'wait'" />
                <a-step title="修改密码" :status="step === 2 ? 'process' : 'wait'" />
            </a-steps>
            <a-form ref="formRef" class="step-content" :model="{ phoneNumber, verificationCodes, newPassword }">
                <template v-if="!showSuccessMessage">
                    <a-form-item v-show="step >= 0" label="手机号" :validate-status="phoneNumberError ? 'error' : ''"
                        :help="phoneNumberError">
                        <a-input ref="phoneInput" v-model:value="phoneNumber" placeholder="请输入手机号"
                            @input="validatePhoneNumber" @blur="setPhoneNumberError" :disabled="step > 0" />
                    </a-form-item>
                    <a-form-item v-show="step >= 1" label="验证码" :validate-status="verificationCodeError ? 'error' : ''">
                        <div class="verification-code">
                            <span class="yuba-text">YuBa - </span>
                            <a-input v-for="(code, index) in verificationCodes" :key="index"
                                v-model:value="verificationCodes[index]" :maxlength="1" @input="focusNext(index)"
                                :disabled="step > 1" ref="codeInput" />
                        </div>
                    </a-form-item>
                    <a-form-item v-show="step >= 2" label="新密码" :validate-status="newPasswordError ? 'error' : ''"
                        :help="newPasswordError">
                        <a-input-password ref="passwordInput" v-model:value="newPassword" placeholder="请输入新密码" />
                    </a-form-item>
                    <div class="button-group">
                        <a-button v-show="step === 0" type="primary" :disabled="!isPhoneNumberValid"
                            @click="debouncedVerifyPhoneNumber">发送验证码</a-button>
                        <a-button v-show="step === 1" type="primary" :disabled="!isVerificationCodeValid"
                            @click="debouncedVerifyCode">验证验证码</a-button>
                        <a-button v-show="step === 2" type="primary" :disabled="!isNewPasswordValid"
                            @click="debouncedChangePassword">修改密码</a-button>
                        <a-button v-show="step > 0 && !userStore.userId" @click="goBack" style="margin-left: 10px;">返回</a-button>
                    </div>
                </template>
                <div v-if="showSuccessMessage" class="success-message">
                    <p>密码修改成功，{{ countdown }}秒后自动跳转到登录页面。</p>
                    <a-button type="link" @click="navigateToLogin">立即跳转登录页</a-button>
                </div>
            </a-form>
        </div>
    </div>

</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { sendSmsCaptcha, existUser, updatePassword, verifySmsCaptcha } from '@/api/front/user/index';
import { useRouter } from 'vue-router';
import { debounce } from 'lodash';
import { getToken } from '@/utils/auth';

const userStore = useUserStore();
const router = useRouter();
const phoneNumber = ref('');
const originalPhoneNumber = ref('');
const verificationCodes = ref(['', '', '', '']);
const newPassword = ref('');
const step = ref(0);
const formRef = ref();

const phoneNumberError = ref('');
const verificationCodeError = ref('');
const newPasswordError = ref('');
const showSuccessMessage = ref(false);
const countdown = ref(5);
const loading = ref(false);
const title = ref('忘记密码');

const phoneInput = ref(null);
const codeInput = ref(null);
const passwordInput = ref(null);

const isPhoneNumberValid = computed(() => {
    return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(phoneNumber.value);
});

const isVerificationCodeValid = computed(() => {
    return verificationCodes.value.join('').length === 4;
});

const isNewPasswordValid = computed(() => {
    return newPassword.value.length >= 6;
});

const validatePhoneNumber = () => {
    if (isPhoneNumberValid.value) {
        phoneNumberError.value = '';
    }
};

const setPhoneNumberError = () => {
    if (!isPhoneNumberValid.value) {
        phoneNumberError.value = '手机号格式不正确';
    }
};

const handleVerifyPhoneNumber = () => {
    loading.value = true;
    formRef.value.validateFields(['phoneNumber']).then(() => {
        existUser(phoneNumber.value).then(response => {
            if (response.data) {
                sendSmsCaptcha(phoneNumber.value).then(() => {
                    step.value = 1;
                    phoneNumberError.value = '';
                    focusInput();
                }).catch(() => {
                    phoneNumberError.value = '发送验证码失败';
                }).finally(() => {
                    loading.value = false;
                });
            } else {
                phoneNumberError.value = '手机号不存在';
                loading.value = false;
            }
        }).catch(() => {
            phoneNumberError.value = '验证用户失败';
            loading.value = false;
        });
    }).catch(error => {
        phoneNumberError.value = error.errorFields[0]?.errors[0] || '';
        loading.value = false;
    });
};

const handleVerifyCode = () => {
    loading.value = true;
    formRef.value.validateFields(['verificationCodes']).then(() => {
        const code = verificationCodes.value.join('');
        const phoneToVerify = userStore.userId ? originalPhoneNumber.value : phoneNumber.value;
        verifySmsCaptcha(phoneToVerify, code).then(response => {
            if (response.data) {
                step.value = 2;
                verificationCodeError.value = '';
                focusInput();
            } else {
                verificationCodeError.value = '验证码错误';
                verificationCodes.value = ['', '', '', ''];
                nextTick(() => {
                    const firstInput = document.querySelector('.verification-code input') as HTMLInputElement;
                    firstInput.focus();
                });
            }
        }).catch(() => {
            verificationCodeError.value = '验证码验证失败';
        }).finally(() => {
            loading.value = false;
        });
    }).catch(error => {
        verificationCodeError.value = error.errorFields[0]?.errors[0] || '';
        loading.value = false;
    });
};

const handleChangePassword = () => {
    loading.value = true;
    formRef.value.validateFields(['newPassword']).then(() => {
        const phoneToUpdate = userStore.userId ? originalPhoneNumber.value : phoneNumber.value;
        updatePassword({ username: phoneToUpdate, password: newPassword.value }).then(() => {
            console.log('密码修改成功');
            newPasswordError.value = '';
            if (userStore.userId && getToken()) {
                userStore.logout();
            }
            showSuccessMessage.value = true;
            startCountdown();
        }).catch(() => {
            newPasswordError.value = '密码修改失败';
        }).finally(() => {
            loading.value = false;
        });
    }).catch(error => {
        newPasswordError.value = error.errorFields[0]?.errors[0] || '';
        loading.value = false;
    });
};

const startCountdown = () => {
    const interval = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value -= 1;
        } else {
            clearInterval(interval);
            navigateToLogin();
        }
    }, 1000);
};

const navigateToLogin = () => {
    router.replace({
        path: '/login'
    });
};

const debouncedVerifyPhoneNumber = debounce(handleVerifyPhoneNumber, 300);
const debouncedVerifyCode = debounce(handleVerifyCode, 300);
const debouncedChangePassword = debounce(handleChangePassword, 300);

const focusNext = (index: number) => {
    if (index < verificationCodes.value.length - 1 && verificationCodes.value[index]) {
        const nextInput = document.querySelectorAll('.verification-code input')[index + 1] as HTMLInputElement;
        nextInput.focus();
    }
};

const goBack = () => {
    if (step.value > 0) {
        step.value -= 1;
        focusInput();
    }
};

const focusInput = () => {
    nextTick(() => {
        if (step.value === 0 && phoneInput.value) {
            phoneInput.value.focus();
        } else if (step.value === 1 && codeInput.value) {
            const firstCodeInput = document.querySelector('.verification-code input') as HTMLInputElement;
            firstCodeInput.focus();
        } else if (step.value === 2 && passwordInput.value) {
            passwordInput.value.focus();
        }
    });
};

onMounted(() => {
    if (userStore.userId) {
        title.value = '修改密码';
        originalPhoneNumber.value = userStore.name;
        phoneNumber.value = userStore.name.replace(/.(?=.{4})/g, '*');
        step.value = 1;
        sendSmsCaptcha(originalPhoneNumber.value).then(() => {
            console.log('验证码已发送');
        }).catch(() => {
            phoneNumberError.value = '发送验证码失败';
        });
    }
    focusInput();
});
</script>

<style scoped>
:deep(.ant-input-password) {
    padding: 0;
}

:deep(.ant-input-password-icon) {
    margin-right: 0;
    height: 100%;
    display: flex;
    align-items: center;
}

:deep(.ant-input-affix-wrapper) {
    padding: 0 11px;
}

:deep(.ant-input-affix-wrapper-focused),
:deep(.ant-input-affix-wrapper:focus) {
    padding: 0 11px;
}

:deep(.ant-input-focused),
:deep(.ant-input:focus) {
    outline: none;
    box-shadow: none !important;
}

:deep(.ant-input-affix-wrapper-focused .ant-input) {
    width: 100%;
    outline: none;
}
.change-password-container {
    max-width: 500px;
    min-height: 425px;
    margin: 50px auto;
}
.change-password {
    
    padding: 30px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    min-height: 280px;
}

.change-password h2,
.button-group {
    text-align: center;
}

.steps {
    margin-bottom: 20px;
}

.step-content {
    margin-top: 25px;
}

.verification-code {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-bottom: 10px;
}

.yuba-text {
    font-size: 18px;
    font-weight: bold;
    margin-right: 8px;
}

.verification-code input {
    width: 40px;
    text-align: center;
}

.button-group {
    margin-top: 30px;
}

.success-message {
    text-align: center;
    margin-top: 20px;
}

.error {
    color: red;
    margin-top: 8px;
}
</style>
